<template>
  <div
    v-if="
      $store.state.edit.row &&
        $store.state.main.entry.sources &&
        $store.state.edit.row.rules
    "
  >
    <div
      class="form-group mt15"
      v-for="(rule, index) in $store.state.edit.row.rules"
      :key="index"
    >
      <el-form-item :label="m(rule.caption)" label-width="120px">
        <template v-if="$store.state.main.entry.sources[rule.source]">
          <el-select
            size="mini"
            v-model="values[rule.field]"
            filterable
            clearable
            :multiple="rule.type == 'multiselect'"
          >
            <el-option
              v-for="k in Object.keys(
                $store.state.main.entry.sources[rule.source]
              )"
              :key="k"
              :label="m($store.state.main.entry.sources[rule.source][k])"
              :value="k"
            >
            </el-option>
          </el-select>
        </template>
        <template v-else-if="rule.type == 'text'">
          <el-input
            auto-complete="off"
            size="mini"
            style="width: 80%"
            v-model="values[rule.field]"
          >
          </el-input>
        </template>
      </el-form-item>
    </div>
    <!-- </div> -->
  </div>
</template>

<script>
import { m } from "@/store/yg/common/local";

export default {
  data() {
    return {
      values: {}
    };
  },
  props: ["field"],
  methods: {
    m(k) {
      return m(k, true);
    },
    loadOptions() {
      if (!this.$store.state.edit.row.rules) {
        return;
      }

      for (var i = 0; i < this.$store.state.edit.row.rules.length; ++i) {
        var rule = this.$store.state.edit.row.rules[i];
        if (!this.$store.state.main.entry.sources[rule.source]) {
          this.$store.dispatch("loadOptionSource", rule.source);
        }
      }
      return "";
    },
    callbefore() {
      if (this.values) {
        this.$store.state.edit.row["displayRule"] = JSON.stringify(this.values);
      }
    },
    init() {
      if (this.$store.state.edit.row["displayRule"]) {
        this.values = JSON.parse(this.$store.state.edit.row["displayRule"]);
      }
      this.loadOptions();
    }
  },
  created() {
    var rules = this.$store.state.edit.row.rules;
    if (!rules) {
      rules = [];
    }
    rules.push({
      caption: "permission",
      field: "ROLE_ID",
      type: "multiselect",
      source: "roleSource"
    });
    for (var i = 0; i < rules.length; ++i) {
      this.values[rules[i].field] = [];
    }
    this.values = JSON.parse(JSON.stringify(this.values));
    this.$store.state.edit.row.rules = rules;
    this.init();
  }
};
</script>
